const { exec } = require("../db/mysql");
var fs = require("fs");
var path = require("path");
const xss = require("xss");
// 校验登录
const loginCheck = (id) => {
  const sql = `select user_email from user where user_id='${id}'`;
  return exec(sql).then((rows) => {
    return rows[0] || {};
  });
};

const login = (user_email, user_pwd) => {
  user_email = escape(user_email);
  user_pwd = escape(user_pwd);
  //加密密码
  //   user_pwd = genPassword(user_pwd);
  const sql = `select * from user where user_email='${user_email}' and user_pwd='${user_pwd}'`;
  //   console.log(sql);
  return exec(sql).then((rows) => {
    return rows[0] || {};
  });
};
// 用户注册模块
const add_u = (userData = {}) => {
  const user_email = escape(userData.user_email);
  let user_pwd = escape(userData.user_pwd);
  //加密密码
  //   user_pwd = genPassword(user_pwd);

  const selSql = `select user_email from user where user_email='${user_email}'`;
  return exec(selSql).then((rows) => {
    if (rows[0] === undefined) {
      const sql = `insert into user (user_email, user_pwd) values('${user_email}','${user_pwd}');`;
      console.log(sql);
      return exec(sql).then((insertData) => {
        return {
          id: insertData.insertId,
          msg: "添加成功",
          code: 0,
        };
      });
    } else {
      return {
        msg: "该用户已经存在",
        code: -1,
      };
    }
  });
};

const update_u = (id, userData = {}) => {
  let user_email = escape(userData.user_email);
  let user_pwd = escape(userData.user_pwd);

  const sql = `update user set user_email='${user_email}',user_pwd='${user_pwd}' where user_id=${id}`;
  return exec(sql).then((updateData) => {
    if (updateData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};

const get_u = () => {
  const sql = `select * from user`;
  return exec(sql);
};

const del_u = (id) => {
  console.log(id);
  const sql = `delete from user where user_id=${id}`;
  return exec(sql).then((delData) => {
    if (delData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};

module.exports = {
  login,
  get_u,
  update_u,
  del_u,
  add_u,
};
